package com.example.medical.utils.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Configuration
@Slf4j
public class EverythingConfig {

    public String Upload(MultipartFile file) throws Exception{
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        File path = new File(ResourceUtils.getURL("classpath:static").getPath());
        if(!path.exists()) {
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(),"/target/classes/static/upload/");
        if(!upload.exists()) {
            upload.mkdirs();
        }
        String fileName = new Date().getTime()+"."+fileExt;
        File dest = new File(upload.getAbsolutePath()+"/"+fileName);
        file.transferTo(dest);
        return fileName;
    }

    /**
     * 汇总到同一个文件夹根据各自的数据库id区分
     */
    public String ImageStorage(MultipartFile uploadFile, HttpServletRequest request){
        if (uploadFile.isEmpty()) {
            return "请选择你要上传的图片";
        }
        String uploadImage="res/Images/";
        String realPath = new String("src/main/resources/"+uploadImage);
        System.out.println("尝试输出文件路径:"+realPath);
        File file= new File(realPath);
        if (!file.isDirectory()) {
            System.out.println("该文件夹不存在，已新建文件夹");
            file.mkdirs();
        }

        String imageName=uploadFile.getOriginalFilename();
        imageName=UUID.randomUUID().toString()+imageName.substring(imageName.lastIndexOf("."),imageName.length());

        try {
            String imagePath=realPath+imageName;
            try {
                byte[] srcFileBytes = uploadFile.getBytes();
                OutputStream f=new FileOutputStream(imagePath);
                f.write(srcFileBytes);
                f.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            String path=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"+uploadImage;
            String thumb=imageName;
            return thumb;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "上传失败";
    }

    /**
     * 按添加时间分配文件位置
     */
    public String ImageStroageForTime(MultipartFile uploadFile, HttpServletRequest request){
        String UPLOAD_PATH_PREFIX = "res/Public/Uploads/small/";
        if(uploadFile.isEmpty()){
            //返回选择文件提示
            return "请选择上传文件";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
        String realPath = new String("src/main/webapp/" + UPLOAD_PATH_PREFIX);
        System.out.println("-----------上传文件保存的路径【"+ realPath +"】-----------");//src/main/webapp/res/Public/Uploads/small/
        String format = sdf.format(new Date());//给一个时间
        System.out.println("时间格式："+format);
        //存放上传文件的文件夹
        File file = new File(realPath + format);//==新建文件夹
        System.out.println("-----------存放上传文件的文件夹【"+ file +"】-----------");
        System.out.println("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【"+ file.getAbsolutePath() +"】-----------");
        if(!file.isDirectory()){
            //递归生成文件夹
            file.mkdirs();
        }
        //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
        //单纯改个名字
        String oldName = uploadFile.getOriginalFilename();
        System.out.println("-----------文件原始的名字【"+ oldName +"】-----------");
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
        System.out.println("-----------文件要保存后的新名字【"+ newName +"】-----------");
        try {
            //不使用MultipartFile.transferTo，把 MultipartFile 对象转字节流后使用 FileOutputStream 手动保存二进制流：
            //这里的actualPath是相对项目根目录的路径 例如：相对项目根目录的路径【src/main/webapp/res/Public/Uploads/small/2023/06/27/b900c537-20d6-4909-8768-a43a12b2936c.jpg】
            String actualPath=realPath+format+newName;
            System.out.println("-----------相对项目根目录的路径【"+actualPath+"】-----------");
            try {
                byte[] srcFileBytes = uploadFile.getBytes();
                OutputStream f = new FileOutputStream(actualPath);
                f.write(srcFileBytes);
                f.close();
            } catch (FileNotFoundException e) {
                log.info("File not found");
                log.info(actualPath);
                e.printStackTrace();
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
//            String httpPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/res/Public/Uploads/small/" + format + newName;
            String httpPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +request.getContextPath()+ "/"+UPLOAD_PATH_PREFIX+ format + newName;
            log.info("-----------网络访问路径：【"+ httpPath +"】-----------");
            //需要保存到数据库字段的格式值
            String thumb=format+newName;
            return thumb;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败!";
    }
}
